<template>
  <div style="overflow:hidden;height:100%;width:100%;position:relative">
    <div
      v-if="editingIndex!=null"
      class="layer-actionbar"
      style="position:absolute;top:0px;height:22px;width:100%;background:#ffffff;z-index:1"
    >
      <el-button type="text" title="删除" @click="layerDeleteHandler(editingIndex)"
        ><i class="el-icon-delete"></i
      ></el-button>
      <el-button type="text" title="复制" @click="layerCopyHandler(editingIndex)"
        ><i class="el-icon-document-copy"></i
      ></el-button>
      <el-button type="text" title="编辑" @click="layerEditHandler(editingIndex)"
        ><i class="el-icon-edit"></i
      ></el-button>
      <el-button
        type="text"
        :title="component.show ? '隐藏' : '显示'"
        @click="component.show = !component.show"
      >
        <i class="el-icon-camera" v-if="!component.show"></i>
        <i class="el-icon-camera-solid" v-else></i>
      </el-button>
      <el-button
        type="text"
        :title="component.position.backgound ? '取消背景' : '设为背景'"
        @click="handlerIsBackgroundChange(activeIndex)"
      >
        <i class="el-icon-picture-outline" v-if="!component.position.backgound"></i>
        <i class="el-icon-picture" v-else></i>
      </el-button>
      <el-button type="text" title="另存为视图组件" @click="saveAsView(editingIndex)"
        ><i class="el-icon-copy-document"></i
      ></el-button>
      <el-button
        type="text"
        title="另存为中间件"
        @click="saveAsMiddleware(editingIndex)"
        ><i class="el-icon-collection"></i
      ></el-button>
    </div>
    <div style="overflow-y:auto;height:100%;width:100%;">
      <div style="overflow: hidden;margin-top:22px">
        <draggable
          v-model="orderedcomponents"
          @update="datadragEnd"
          v-bind="{ draggable: '.box-card', animation: 500 }"
        >
          <transition-group>
            <div
              class="box-card"
              style="width:180px;height:20px;float:left; margin:3px"
              v-for="(item, index) in orderedcomponents"
              :key="index"
            >
              <el-button
                type="text"
                style="padding:0px;"
                @click="onLayerSelected(index, item)"
              >
                <div style="width:100%;height:100%;position:relative">
                  <img
                    width="180"
                    height="20"
                    :src="
                      ((item.view || {}).cover || {}).fileId | getResourceUrl
                    "
                    class="image"
                  />
                  <div
                    class="div-layeritem-title"
                    v-bind:style="{
                      background:
                        activeIndex == index ? 'rgb(236,82,50,0.8)' : 'dimgrey'
                    }"
                  >
                    <i class="el-icon-view" style="color:#ffff33" v-if="item.show||item.position.backgound"></i>
                    {{ (item.view || {}).name + "/" + (item.view || {}).code }}
                  </div>
                </div>
              </el-button>
            </div>
          </transition-group>
        </draggable>
        <div class="clear" style="clear:both;"></div>
        <!-- 弹窗抽屉 -->
        <el-drawer
          title="组件编辑"
          size="60%"
          :visible.sync="isShowComponentEdit"
          :with-header="false"
          :modal="false"
          direction="ltr"
          @opened="componentEditOpenHandler"
          @closed="componentEditCloseHandler"
        >
          <div style="width:100%;height:100vh;overflow:auto;">
            <componentEdit
              ref="componentEdit"
              :component="component"
            ></componentEdit>
          </div>
        </el-drawer>

        <div class="clearfix"></div>
      </div>
    </div>
  </div>
</template>

<script>
import resourceApi from "@/api/resource";
import componentEdit from "./componentEdit";

//拖拽排序
import draggable from "vuedraggable";

import { uuid } from "@/utils/index";

export default {
  components: { componentEdit, draggable },
  filters: {
    getResourceUrl(fileId) {
      return resourceApi.getResourceUrl(fileId);
    }
  },
  props: {
    components: {
      default: () => []
    },
    activeIndex: 0
  },
  watch:{
    activeIndex(){
      if(this.activeIndex!=null)
        this.editingIndex = this.activeIndex;
    }
    
  },
  data() {
    return {
      isShowComponentEdit: false,
      editingIndex: null
    };
  },
  computed: {
    orderedcomponents: {
      get() {
        return this.components.filter(c => true);
      },
      set(v) {
        //console.log(this.components , v)

        for (let i = 0; i < v.length; i++) {
          v[i].order = i;
        }

        this.$emit("change", v);
      }
    },
    component() {
      let com = this.components[this.editingIndex];
      if (!com) return {position:{}};
      if (!com.view) {
        this.$set(com, "view", {
          code: "",
          codes: "",
          cover: {
            fileId: "",
            fileName: ""
          },
          description: "",
          headLinks: "",
          id: "",
          name: "",
          resources: [
            {
              fileId: "",
              fileName: ""
            }
          ],
          size: {
            height: 0,
            width: 0
          },
          updateTime: ""
        });
      }

      if (!com.middleware) {
        this.$set(com, "middleware", {
          description: "",
          middleware: {
            fileId: "",
            fileName: ""
          },
          middlewareEntry: "",
          name: "",
          parameters: [
            {
              description: "",
              isPublic: true,
              name: "",
              required: true,
              value: ""
            }
          ],
          push: true,
          systemMiddleware: true,
          systemMiddlewareId: "",
          updateFrequency: 0
        });
      }
      return com;
    }
  },
  methods: {
    layerDeleteHandler(index) {
      debugger
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //删除图层
        this.components.splice(index, 1);
        this.editingIndex = null;
         this.$emit("onSelected", null);
      });
    },
    layerCopyHandler(index) {
      //复制图层
      let oldCom = this.components[index];
      let newCom = JSON.parse(JSON.stringify(oldCom));
      newCom.id = uuid();
      newCom.view.id = uuid();
      //this.components.splice(index, 0, newCom);
      this.components.push(newCom);
    },
    layerEditHandler(index) {
      //this.activeIndex = index;
      this.$emit("onSelected", index);
      this.editingIndex = index;
      this.isShowComponentEdit = true;
    },
    handlerIsBackgroundChange(_index) {
      //设为背景变化
      //除了当前项，其它的都设为 不勾选

      this.components[_index].position.backgound = !this.components[_index]
        .position.backgound;
      this.components[_index].show = !this.components[_index].position
        .backgound;
      for (let index = 0; index < this.components.length; index++) {
        if (_index == index) continue;
        this.components[index].position.backgound = false;
      }
    },
    onLayerSelected(index) {
      this.editingIndex = index;
      this.$emit("onSelected", index);
    },
    saveAsView(index) {
      //另存为视图
      let view = this.components[index].view;
      this.$store
        .dispatch("viewComponent/create", { name: view.name })
        .then(res => {
          return res;
        })
        .then(res => {
          view.id = res.id;
          this.$store.dispatch("viewComponent/update", view).then(res => {
            this.loading = false;
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
        });
    },
    saveAsMiddleware(index) {
      debugger;
      //另存为中间件
      let view = this.components[index].view;
      let middleware = this.components[index].middleware;
      middleware.cover = view.cover;
      this.$store.dispatch("middleware/create", middleware).then(res => {
        this.loading = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      });
    },
    datadragEnd(evt) {
      evt.preventDefault();
      console.log("拖动前的索引 :" + evt.oldIndex);
      console.log("拖动后的索引 :" + evt.newIndex);
      console.log(this.components);
    },
    componentEditOpenHandler() {
      let com = this.components[this.editingIndex];
      this.$refs.componentEdit.setBodyValue(com.view.htmlbody);
      this.$refs.componentEdit.setScriptValue(com.view.codes);
    },
    componentEditCloseHandler() {
      let com = this.components[this.editingIndex];
      com.view.htmlbody = this.$refs.componentEdit.getBodyValue();
      com.view.codes = this.$refs.componentEdit.getScriptValue();
    }
  }
};
</script>

<style>
.div-layeritem .el-button {
  padding: 0px;
}
.div-layeritem {
  padding: 0px;
  position: absolute;
  width: 100%;
  height: 40px;
  text-align: left;
  bottom: 0px;
  background: rgba(266, 255, 255, 0.8);
}
.div-layeritem-title {
  padding: 0px;
  position: absolute;
  width: 100%;
  height: 20px;
  line-height: 20px;
  text-align: left;
  top: 0px;
  color: #ffffff;
  font-size: 10px;
  background: dimgrey;
}
.clearfix {
  clear: both;
}

/*图岑他工具面板按钮 */
.layer-actionbar .el-button {
  padding: 2px;
}
</style>
